﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.WebPages;
using Eksponent.RazorRocks.Helpers;

namespace Eksponent.RazorRocks
{
    public class TemplateHelperResult : HelperResult
    {
        internal readonly IDictionary<string, object> ReturnValues;

        internal readonly Action<TextWriter> Action;

        public TemplateHelperResult(Action<TextWriter> action, IDictionary<string, object> returnValues = null)
            : base(action)
        {            
            ReturnValues = returnValues;
            Action = action;
        }

        /// <summary>
        /// Wraps the result from the template in html that can use the return values from the template
        /// </summary>
        /// <param name="wrapper">The wrapper function.</param>
        /// <returns></returns>
        public HelperResult Wrap(Func<TemplateWrapArgs, HelperResult> wrapper)
        {                        
            return new HelperResult(w=>
                                        {                                            
                                            var result = new HtmlString(this.ToString());
                                            wrapper(new TemplateWrapArgs()
                                                        {
                                                            ReturnValues = new DynamicDictionary(ReturnValues),
                                                            Output = result
                                                        }).WriteTo(w);
                                        });
        }
    }

    public class TemplateWrapArgs
    {
        public dynamic ReturnValues { get; set; }

        public HtmlString Output { get; set; }
    }       
}
